package com.pys.beans;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.apache.commons.lang.StringUtils;

import com.pys.common.beans.BaseBean;
import com.pys.pojo.PysProje;
import com.pys.service.ProjeService;
import com.pys.utils.FacesUtils;

@ManagedBean
@ViewScoped
public class ProjeBean extends BaseBean implements Serializable {
	private String ad;
	private boolean durum = true;
	private List<PysProje> list;
	private PysProje selectedProje;

	public ProjeBean() {
		refreshList();
	}

	/*
	 * ACTIONS
	 */
	public void refreshList() {
		ProjeService projeService = new ProjeService();
		list = projeService.getAllList(false);
	}

	public void saveAction() {
		if (StringUtils.isBlank(ad)) {
			FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR,
					"VALIDATION_PROJE_AD");
			return;
		}
		ProjeService projeService = new ProjeService();
		if (selectedProje == null) {
			PysProje pysProje = new PysProje();
			pysProje.setAd(ad);
			pysProje.setDurum(durum);
			pysProje.setPysKullanici(FacesUtils.getUserSession()
					.getCurrentUser());
			pysProje.setOlusturmaTarih(new Date());
			projeService.save(pysProje);
		} else {
			selectedProje.setAd(ad);
			selectedProje.setDurum(durum);
			selectedProje.setPysKullanici(FacesUtils.getUserSession()
					.getCurrentUser());
			selectedProje.setGuncellemeTarih(new Date());
			projeService.update(selectedProje);
		}
		refreshList();
		clear();
		FacesUtils.successMessage();
	}

	public void deleteAction() {
		ProjeService projeService = new ProjeService();
		selectedProje.setDeleted(true);
		projeService.update(selectedProje);
		refreshList();
		clear();
		FacesUtils.successMessage();
	}

	public void updateAction() {
		ad = selectedProje.getAd();
		durum = selectedProje.isDurum();
	}

	public void clear() {
		selectedProje = null;
		ad = null;
		durum = true;
	}

	/*
	 * GETTER-SETTER
	 */
	public String getAd() {
		return ad;
	}

	public void setAd(String ad) {
		this.ad = ad;
	}

	public List<PysProje> getList() {
		return list;
	}

	public void setList(List<PysProje> list) {
		this.list = list;
	}

	public PysProje getSelectedProje() {
		return selectedProje;
	}

	public void setSelectedProje(PysProje selectedProje) {
		this.selectedProje = selectedProje;
	}

	public boolean isDurum() {
		return durum;
	}

	public void setDurum(boolean durum) {
		this.durum = durum;
	}
}
